const Koa = require('koa');
const router = require('koa-Router')();
const bodyParser = require('koa-bodyparser');
const cors = require('@koa/cors')
const fs = require('fs');
const path = require('path');
var jwt = require('jsonwebtoken');
const Mock = require('mockjs')
const app = new Koa();
// const WebSocket = require('ws');
const serve = require('koa-static');
const multer = require('@koa/multer');
// const wss = new WebSocket.Server({ port: 8080 });

const OSS = require('ali-oss')

const userJson = path.join(__dirname, './user.json',)
app.use(serve(__dirname + '/public'));

const storage = multer.diskStorage({
    destination: function (req, file, cb) {  //存储目录
        cb(null, './public')
    },
    filename: function (req, file, cb) {
        console.log(file);
        cb(null, file.originalname)  //存储名字
    }
})


app.use(cors());
app.use(bodyParser());

// 为你推荐数据渲染
const TabsoneData = Mock.mock({
    'list|25': [
        {
            'id|+1': 1,
            'image|1': ['https://pub-cdn-oss.chuangkit.com/ad_position/6e54a105b22b4c71a88e5c83908da221', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/21/8beee56d-5edc-4ed3-b2e9-9496fbe863c8_thumb?v=1726121404000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/22/f430e114-b69e-443d-8b35-21496aee87eb_thumb?v=1724914201000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/31/cd88199f-05e5-4744-9e9f-340501ac0a47_thumb?v=1722395040000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2023/08/23/0843c6f8-fa37-4a45-a586-5deec5338a7b_thumb?v=1725517200000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp']
        }
    ]
})
console.log(TabsoneData.list);
// 中秋
const TabstwoData = Mock.mock({
    'list|25': [
        {
            'id|+1': 1,
            'image|1': ['https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/16/43b46e34-d1a8-4005-b556-8bc8b0cb955e_thumb?v=1723794121000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/21/1173f10c-2e38-4319-b0a7-87f341d7b148_thumb?v=1724203921000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/31/c4db7baf-cf5f-4176-93df-f5c92206f96b_thumb?v=1722405605000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2023/07/27/0125710f-c1ea-417a-9850-e439105954be_thumb?v=1690422247000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/31/233b44f3-d3b9-4487-8743-e129e0ccf962_thumb?v=1722405603000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp']
        }
    ]
})

// 喜报
const TabsthreeData = Mock.mock({
    'list|25': [
        {
            'id|+1': 1,
            'image|1': ['https://pub-cdn-oss.chuangkit.com/designTemplate/2023/11/20/b028f2cb-7582-4d04-8d8c-26433a8c1891_thumb?v=1720750200000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/15/7546858f-68de-4ec7-9696-536808d0f82b_thumb?v=1721109901000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/31/74820835-fb2b-44a6-9acc-c74158620fb5_thumb?v=1722415443000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2022/12/28/7643c981-21c7-4be5-8a1b-2364f0ebf761_thumb?v=1717815291000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/16/df0847bd-f2b8-4ece-8bc5-dfe4408a3f94_thumb?v=1721097722000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp']
        }
    ]
})

// 热门推荐
const HotData = Mock.mock({
    'list|125': [
        {
            'id|1': 1,
            'image|1': ['https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/27/32ca1d79-dab5-4df6-a303-587dfbb81ac2_thumb?v=1724724960000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2023/08/19/b9e9a8c2-a8c6-4ba3-8096-383bcab08379_thumb?v=1692375901000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/26/96c0e803-eeb4-437f-9ae9-fc845f6a2657_thumb?v=1721980082000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/30/f6f8d928-1c6a-454b-ab74-60d1c4defd13_thumb?v=1724982242000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/30/8091832e-0124-4e39-b95c-5104e168351b_thumb?v=1724984521000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/16/63a2c43d-b9b2-451c-8ea9-d15ba3b9f4a7_thumb?v=1724737507000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp']
        }
    ]
})

// 最新上传
const NewData = Mock.mock({
    'list|125': [
        {
            'id|+1': 1,
            'image|1': ['https://pub-cdn-oss.chuangkit.com/designTemplate/2024/09/13/bb0ed1d0-f314-4d81-8423-30ef237b533c_thumb?v=1726217400000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/09/13/412182fb-fd19-4330-9683-9dbae857c631_thumb?v=1726237920000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/09/13/2d1de23a-4c4e-43fb-bb3c-4113f6422738_thumb?v=1726217160000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/09/13/edcd6034-2dab-4b99-910b-799832644ae1_thumb?v=1726216683000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/09/13/8c84b8ed-ae90-4063-b5c9-a6afc24eb0eb_thumb?v=1726216680000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/09/13/fb58d236-bbe9-4d9c-8544-5f55f77cceaf_thumb?v=1726213800000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70']
        }
    ]
})

// 最多使用
const ManyData = Mock.mock({
    'list|125': [
        {
            'id|+1': 1,
            'image|1': ['https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/31/24bbaea4-b19c-41bf-94d6-0e24e6c704f4_thumb?v=1726019403000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/31/eb18cbfc-dd9e-4a81-b290-f86c8748633b_thumb?v=1723011603000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/31/a0de18eb-86f8-4028-8470-04f553c28b02_thumb?v=1724982602000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/30/6b1f97c4-ef4a-4b51-9a8c-81a5e31a96bd_thumb?v=1725464706000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/09/23c1f744-d3dc-4930-aaeb-62a079f5c4ae_thumb?v=1723196400000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/16/8e8f2fd7-a7f7-4db9-bb53-d0e03bc7cfb5_thumb?v=1723801684000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp%2Fsharpen%2F70']
        }
    ]
})

// 自定义函数生成指定格式的随机时间
const getRandomDateTime = () => {
    let year = Math.floor(Math.random() * (2025 - 2023) + 2023); // 随机年份从2023到2025
    let month = Math.floor(Math.random() * 12 + 1).toString().padStart(2, '0'); // 随机月份
    let day = Math.floor(Math.random() * 31 + 1).toString().padStart(2, '0'); // 随机日期
    let hours = Math.floor(Math.random() * 24).toString().padStart(2, '0'); // 随机小时
    let minutes = Math.floor(Math.random() * 60).toString().padStart(2, '0'); // 随机分钟
    let seconds = Math.floor(Math.random() * 60).toString().padStart(2, '0'); // 随机秒钟

    return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`; // 拼接成完整格式
}
// 表格数据
const guoTableData = Mock.mock({
    'tab|58': [
        {
            'key|+1': 1,
            'name': '@cname',
            'name2': '@cname',
            'shopname|1': ['老果记自营店', '果牛群', '乐开花', '杭辉果业', '鸣笛'],
            'phone': /^1[3-9]\d{9}$/,
            'address': '浙江省杭州市余杭区博园路8号 杭州模版开发市场南门',
            // 生成随机的订单号，ORDER + 时间戳 + 6位随机数字
            'bill': `E${+new Date()}${Math.floor(Math.random() * 1000000)}`.slice(0, 20),
            'types|1': ['充值', '订单消费', '退款'],
            'status|1': ['待付款', '待发货', '待收货', '已完成', '已关闭'],
            'watertypes|1': ['收入', '支出'],
            'desc': '@ctitle(30)',
            'time': getRandomDateTime(),
            'money': '@float(1, 2000, 2, 2)',
            'image|1': ['https://pub-cdn-oss.chuangkit.com/designTemplate/2023/08/15/2cb246c4-5e7f-4f7c-9b96-3d9418dd2088_thumb?v=1726712100000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/16/90689f8a-b494-485b-be59-27a10a1cac89_thumb?v=1727249103000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/23/267ba2e0-087b-4a91-b6e5-29d4c4d30da1_thumb?v=1724394720000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/07/29/9dbaed92-fd60-4f95-8de2-8e866daacc40_thumb?v=1727104202000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/09/24/4fe320cf-d631-4222-a02e-31344f2acd1b_thumb?v=1727142600000&imageMogr2%2Fthumbnail%2F400x%3E%2Fformat%2Fwebp']
        }
    ]
})
const getRandomDateTime1 = () => {
    let year = Math.floor(Math.random() * (2025 - 2023) + 2023); // 随机年份从2023到2025
    let month = Math.floor(Math.random() * 12 + 1).toString().padStart(2, '0'); // 随机月份
    let day = Math.floor(Math.random() * 31 + 1).toString().padStart(2, '0'); // 随机日期
    let hours = Math.floor(Math.random() * 24).toString().padStart(2, '0'); // 随机小时
    let minutes = Math.floor(Math.random() * 60).toString().padStart(2, '0'); // 随机分钟
    let seconds = Math.floor(Math.random() * 60).toString().padStart(2, '0'); // 随机秒钟

    return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`; // 拼接成完整格式
}
// 商品数据
const guoGoodsTable = Mock.mock({
    'tabs|10': [
        {
            'key|+1': 1,
            'shopname|1': ['老果记自营店', '果牛群', '乐开花', '杭辉果业', '鸣笛'],
            'title': '@ctitle(30)',
            'date': getRandomDateTime1(),
            'address': '台湾',
            'money': '@float(1, 2000, 2, 2)',
            'goodsmoney|300-1200': 300,
            'type|1': ['上传', '热门', '自主'],
            'typex|1': ['海报', '小红书', '电商'],
            'butype|1': ['上架', '下架'],
            'image|1': ['https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/16/60dfc98c-3d7f-4043-a5a6-9808019d1737_thumb?v=1723800483000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/16/d231862c-baee-4366-94b2-1ec65673a4db_thumb?v=1727409901000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2024/08/16/4c233c80-3a8a-4628-bcd7-08608537000e_thumb?v=1723798680000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2023/08/15/2cb246c4-5e7f-4f7c-9b96-3d9418dd2088_thumb?v=1726712100000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp', 'https://pub-cdn-oss.chuangkit.com/designTemplate/2023/08/02/bccdfbc4-fe98-429e-b41c-459b92cfbb8f_thumb?v=1727232600000&x-oss-process=image%2Fresize%2Cw_400%2Fsharpen%2C100%2Fformat%2Cwebp']
        }
    ]
})
// 为你推荐
router.get('/TabsoneData', ctx => {
    ctx.body = TabsoneData
})
// 中秋
router.get('/TabstwoData', ctx => {
    ctx.body = TabstwoData
})
// 喜报
router.get('/TabsthreeData', ctx => {
    ctx.body = TabsthreeData
})
// 热门推荐
router.get('/HotData', ctx => {
    ctx.body = HotData
})

// 最新上传
router.get('/NewData', ctx => {
    ctx.body = NewData
})

router.get('/ManyData', ctx => {
    ctx.body = ManyData
})

// 表格数据
router.get('/guo/guotable', ctx => {
    ctx.body = guoTableData
})
// 果币商品数据
router.get('/guo/guogoodstable', ctx => {
    ctx.body = guoGoodsTable
})
// 注册
router.post('/api/register', ctx => {
    const {
        phone,
        password
    } = ctx.request.body;
    let user = JSON.parse(fs.readFileSync(userJson, 'utf-8'))
    let flag = user.some(item => item.phone === phone);
    let token = jwt.sign({
        phone,
        password
    }, 'QWERTYUIOP789145');
    if (!flag) {
        let obj = {
            id: +new Date(),
            phone,
            password
        }
        user.push(obj)
        fs.writeFileSync(userJson, JSON.stringify(user))
        ctx.body = {
            code: 200,
            msg: '注册成功',
            token
        }
    } else {
        ctx.body = {
            code: 500,
            msg: '该手机号已被注册'
        }
    }
})


// 登录
router.post('/api/login', ctx => {
    const { phone, password } = ctx.request.body;
    console.log(phone, password);
    let user = JSON.parse(fs.readFileSync(userJson, 'utf-8'));
    let flag = user.find(item => item.phone === phone);
    if (flag) {
        if (flag.password === password) {
            let token = jwt.sign({
                phone
            }, 'QWERTYUIOP789145');
            ctx.body = {
                code: 200,
                msg: '登录成功',
                token
                // accessToken: token // 只返回 accessToken
            }
        } else {
            ctx.body = {
                code: 401,
                msg: '密码错误'
            }
        }
    } else {
        ctx.body = {
            code: 500,
            msg: '未注册，请注册后重新登录'
        }
    }
})

//客服1v1聊天
// const answers = {
//     '工作时间': "我们的工作时间是周一到周五，9:00 - 18:00",
//     '退款': "请联系我们的客服，提供订单信息进行退款",
//     '保修': "产品的保修期是两年，具体情况请查看产品说明",
//     '修改订单': "可以的，请联系客服进行修改",
//     '在吗': "您好，在的亲",
//     "在哪搜索": '您可以到营销热点里面寻找',
//     "我需要查找内容": '好的，请详细说一下!',
//     "可以吗": "当然可以",
//     '默认': '您好，在的亲，请问有什么可以帮助您的吗？'
// }

// wss.on('connection', (ws) => {
//     console.log('新用户连接');
//     ws.on('message', (message) => {
//         console.log(`收到的消息：${message}`);
//         //简单的关键字匹配
//         let response = answers['默认']
//         for (let key in answers) {
//             if (message.includes(key)) {
//                 response = answers[key]
//                 break
//             }
//         }
//         console.log('发送的回复' + response);
//         ws.send(response)
//     })

//     //连接关闭时做一些清理工作
//     ws.on('close', () => {
//         console.log('断开连接');
//     })
// })
// console.log('WebSocket 服务器已启动，监听 ws://localhost:8080');

const upload = multer({ storage: storage })
//本地上传
router.post('/api/ben', upload.single('file'), async (ctx) => {
    console.log('ctx.file', ctx.file);
    let filename = ctx.file.originalname
    ctx.body = {
        code: 200,
        msg: "本地上传成功",
        url: 'http://localhost:30061/' + filename
    }
})

app.use(router);
app.listen(30061);